/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.validation.client.constraints;

import com.cleangwt.validation.client.BaseValidation;
import com.cleangwt.validation.client.Checks;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;

/**
 * The {@link Validation} for {@link Pattern}.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class PatternValidation extends BaseValidation {
  private RegExp pattern;

  /**
   * Creates a pattern validator with the given regexp, message and default group.
   * 
   * @param regexp the regular expression
   * @param message the error message
   */
  public PatternValidation(String value, String message) {
    this(value, "", message, (String[]) null);
  }

  /**
   * Creates a pattern validator with the given regexp, flag, message and groups.
   * 
   * @param regexp the regular expression
   * @param flag the regular expression flag
   * @param message the error message
   * @param groups the groups
   */
  public PatternValidation(String regexp, String flag, String message, String... groups) {
    super(message, groups);
    pattern = RegExp.compile(regexp, flag);
  }

  @Override
  protected boolean isValid(Object[] values) {
    String v = (String) values[0];
    if (Checks.isEmpty(v)) {
      return true;
    }
    MatchResult match = pattern.exec(v);
    if (match == null) {
      return false;
    }
    // Must match the entire string
    return match.getGroup(0).length() == v.length();
  }
}
